package com.shengwei.truck.driver.view.ui.task;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.shengwei.truck.driver.R;
import com.shengwei.truck.driver.bean.Result;
import com.shengwei.truck.driver.bean.task.JsonOrderListData;
import com.shengwei.truck.driver.bean.task.JsonTaskListData;
import com.shengwei.truck.driver.bean.task.OrderItem;
import com.shengwei.truck.driver.bean.task.TaskItem;
import com.shengwei.truck.driver.databinding.FragmentNostartedTaskBinding;
import com.shengwei.truck.driver.utils.MyLogCat;
import com.shengwei.truck.driver.view.adapter.task.OrderListAdapter;
import com.shengwei.truck.driver.view.adapter.task.TaskListAdapter;
import com.shengwei.truck.driver.view.ui.BaseFragment;
import com.shengwei.truck.driver.view.ui.MainActivity;
import com.shengwei.truck.driver.vm.TaskViewModel;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * 任务列表：展示派发给司机的任务单列表，各TAB页重用这一个Fragment类
 */
public class TaskListFragment extends BaseFragment<TaskViewModel, FragmentNostartedTaskBinding> {
    int currentOperate = PULL_REFRESH; //0表示下拉刷新,1表示加载更多
    private static final int PULL_REFRESH = 0; //下拉刷新
    private static final int LOAD_MORE = 1;  //加载更多
    private TaskListAdapter mTaskAdapter;
    private OrderListAdapter mOrderAdapter; //以后要优化，同TaskListAdapter合并为一个
    private List<TaskItem> mTaskList = new ArrayList<>();
    private List<OrderItem> mOrderList = new ArrayList<>();
    private static final String ARG_SECTION_NUMBER = "section_number";
    private static final String ARG_IS_FORWARD = "is_forward";
    int mTaskState = -1;
    int mIsForward = 0;
    int mPageNum = 0; //索引从0开始表示第一页
    int mPageSize =8;
    String TAG = "TaskListFragment";

    public static TaskListFragment newInstance(int taskState, int isForward) {
        TaskListFragment fragment = new TaskListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_SECTION_NUMBER, taskState);
        bundle.putInt(ARG_IS_FORWARD, isForward);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            mTaskState = getArguments().getInt(ARG_SECTION_NUMBER);
            mIsForward = getArguments().getInt(ARG_IS_FORWARD);
            Log.i(TAG,"mTaskState="+mTaskState);
        }
        super.onCreate(savedInstanceState);
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView =  super.onCreateView(inflater,container,savedInstanceState);
        //初始化控件
        initView();
        initLiveDataObersve();
        return rootView;
    }
    @Override
    public void onResume() {
        MyLogCat.i(TAG,"onResume");
        if(MainActivity.mCurTabIndex == 1) {
            MyLogCat.i(TAG,"onResume refresh mTaskState="+mTaskState);
            refreshLoadData();
        }
        super.onResume();
    }
    @Override
    public int getContentViewId() {
        return R.layout.fragment_nostarted_task;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 初始化控件
     */
    public void initView() {
        //配置下拉刷新控件的圆形转圈的颜色
        mDataBinding.refreshLayout.setOnRefreshListener(mRefreshListener);
        int colorCircle1 = mContext.getResources().getColor(R.color.colorPrimary);
        int colorCircle2 = mContext.getResources().getColor(R.color.colorPrimaryDark);
        int colorCircle3 = mContext.getResources().getColor(R.color.colorPrimary);
        mDataBinding.refreshLayout.setColorSchemeColors(colorCircle1,colorCircle2,colorCircle3);

        //配置任务列表控件Recyclerview
        mDataBinding.taskRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mDataBinding.taskRecyclerView.setSwipeItemClickListener(mItemClickListener); // RecyclerView Item点击监听。
        mDataBinding.taskRecyclerView.useDefaultLoadMore(); // 使用默认的加载更多的View。
        mDataBinding.taskRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。

        //新订单列表
        if(mTaskState == 9) {
            mOrderAdapter = new OrderListAdapter(mContext);
            mDataBinding.taskRecyclerView.setAdapter(mOrderAdapter);
        }
        else{  //新任务列表
            mTaskAdapter = new TaskListAdapter(mContext,mTaskState);
            mDataBinding.taskRecyclerView.setAdapter(mTaskAdapter);
        }
    }


    /**
     * 创建liveData观察者，用于监听数据变化，从而更新UI
     */
    private void initLiveDataObersve() {

        //任务列表
        mViewModel.getTaskListLiveData().observe(getViewLifecycleOwner(), new Observer<Result<JsonTaskListData>>() {
            @Override
            public void onChanged(Result<JsonTaskListData> jsonTaskListDataResult) {

                jsonTaskListDataResult.handler(new OnCallback<JsonTaskListData>() {
                    @Override
                    public void onSuccess(JsonTaskListData data) {
                        if(currentOperate == PULL_REFRESH) {
                            dealTaskListForRefresh(data);
                        }
                        else {  //上拉加载更多
                            dealTaskListForLoadMore(data);
                        }
                        mDataBinding.refreshLayout.setRefreshing(false);
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                });
            }
        });

        //计划单列表，与任务列表是不同的接口
        mViewModel.getOrderListLiveData().observe(getViewLifecycleOwner(), new Observer<Result<JsonOrderListData<OrderItem>>>() {
            @Override
            public void onChanged(Result<JsonOrderListData<OrderItem>> jsonTaskListDataResult) {

                jsonTaskListDataResult.handler(new OnCallback<JsonOrderListData<OrderItem>>() {
                    @Override
                    public void onSuccess(JsonOrderListData data) {
                        if(currentOperate == PULL_REFRESH) {
                            dealOrderListForRefresh(data);
                        }
                        else {  //上拉加载更多
                            dealOrderListForLoadMore(data);
                        }
                        mDataBinding.refreshLayout.setRefreshing(false);
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        super.onError(throwable);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                    @Override
                    public void onFailure(String msg) {
                        super.onFailure(msg);
                        mDataBinding.refreshLayout.setRefreshing(false);
                        String loadErroMsg = getResources().getString(R.string.recycler_swipe_load_error);
                        mDataBinding.taskRecyclerView.loadMoreError(0,loadErroMsg);
                    }
                });
            }
        });
    }

    /**
     * 处理  "下拉刷新" 时 从服务器获取到的 “订单列表”，显示到 UI列表上
     * @param orderListData： “订单列表”数据
     */
    public void dealOrderListForRefresh(JsonOrderListData orderListData) {
        //是否有下一页
        int totalpages = orderListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;

        List<OrderItem> orderList =  orderListData.getContent();
        boolean isCurEmptyData = true;
        mOrderList.clear();

        if(orderList != null && orderList.size() > 0) {
            mDataBinding.taskRecyclerView.setVisibility(View.VISIBLE);
            mDataBinding.noDataLayout.setVisibility(View.GONE);
            isCurEmptyData = false;
            mOrderList.addAll(orderList);
        }
        else{
            mDataBinding.taskRecyclerView.setVisibility(View.GONE);
            mDataBinding.noDataLayout.setVisibility(View.VISIBLE);
        }
        mOrderAdapter.notifyOrderItemChange(mOrderList);
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    /**
     * 处理  "上滑加载更多" 时 从服务器获取到的 “订单列表”，显示到 UI列表上
     * @param orderListData： “订单列表”数据
     */
    public void dealOrderListForLoadMore(JsonOrderListData orderListData)
    {
        //是否有下一页
        int totalpages = orderListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
        boolean isCurEmptyData = true;
        List<OrderItem> orderItemList =  orderListData.getContent();
        int orderItemSize = orderItemList.size();

        if(orderItemList != null && orderItemSize > 0) {
            int existSize = mOrderList.size();  //已有的条目个数
            isCurEmptyData = false;
            mOrderList.addAll(orderItemList);
            mOrderAdapter.notifyItemRangeInserted(existSize - 1,orderItemSize);
        }
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    /**
     * 处理  "下拉刷新" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForRefresh(JsonTaskListData taskListData)
    {
            //是否有下一页
            int totalpages = taskListData.getTotalPages();
            boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
            List<TaskItem> taskItemList =  taskListData.getContent();
            boolean isCurEmptyData = true;
            mTaskList.clear();

            if(taskItemList != null && taskItemList.size() > 0) {
                mDataBinding.taskRecyclerView.setVisibility(View.VISIBLE);
                mDataBinding.noDataLayout.setVisibility(View.GONE);
                isCurEmptyData = false;
                mTaskList.addAll(taskItemList);
            }
            else{
                mDataBinding.taskRecyclerView.setVisibility(View.GONE);
                mDataBinding.noDataLayout.setVisibility(View.VISIBLE);
            }
            mTaskAdapter.notifyDataSetChanged(mTaskList);
            if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
                mPageNum++;
            }
            mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);

    }
    /**
     * 处理  "上滑加载更多" 时 从服务器获取到的 “任务列表”，显示到 UI列表上
     * @param taskListData： “任务列表”数据
     */
    public void dealTaskListForLoadMore(JsonTaskListData taskListData) {
        //是否有下一页
        int totalpages = taskListData.getTotalPages();
        boolean isHasMore = ((mPageNum + 1) < totalpages)? true:false;
        boolean isCurEmptyData = true;
        List<TaskItem> taskItemList =  taskListData.getContent();

        if(taskItemList != null && taskItemList.size() > 0) {
            int existSize = mTaskList.size();  //已有的条目个数
            isCurEmptyData = false;
            mTaskList.addAll(taskItemList);
            mTaskAdapter.notifyItemRangeInserted(existSize - 1,taskItemList.size());
        }
        if(isHasMore) { //还有更多数据时，页码+1 准备请求下一页
            mPageNum++;
        }
        mDataBinding.taskRecyclerView.loadMoreFinish(isCurEmptyData, isHasMore);
    }

    /**
     * 下拉刷新数据
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshLoadData();
        }
    };

    /**
     * 上拉时加载更多
     */
    private SwipeMenuRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeMenuRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            currentOperate = LOAD_MORE;
            mDataBinding.taskRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mTaskState == 9) {
                        //获取订单列表
                        mViewModel.getPlanOrders(mPageNum,mPageSize);
                    }
                    else if(mTaskState == 5) {  //“已完成”列表现在包括:"已完成(状态为5)，榜单已提交的任务（磅单待审核时任务状态为3,磅单审核不通过时任务状态为4）"
                        //获取"已完成"任务列表
                        mViewModel.getTaskList("3,4,5", mPageNum, mPageSize,mIsForward);
                    }
                    else{
                        //获取任务列表
                        mViewModel.getTaskList(String.valueOf(mTaskState), mPageNum, mPageSize,mIsForward);
                    }
                }
            }, 0);
        }
    };

    /**
     * Item点击监听
     */
    private SwipeItemClickListener mItemClickListener = new SwipeItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {

            Intent i;
            String id = null;

            if(mTaskState == 9) { //订单列表
                OrderItem orderItem =  mOrderList.get(position);
                id = orderItem.getId();
                i = new Intent(mContext, OrderDetailActivity.class);
            }else{   //任务列表
                TaskItem taskItem =  mTaskList.get(position);
                id = taskItem.getId();
                i = new Intent(mContext, TaskDetailActivity.class);
            }
            i.putExtra("id",id);
            startActivity(i);
        }
    };

    /**
     * 第一次加载数据或下拉刷新
     */
    private void refreshLoadData() {
        mPageNum = 0;
        currentOperate = PULL_REFRESH;
        Log.i(TAG,"taskStatus="+mTaskState+",will getList");

        if(mTaskState == 9) {
            //获取订单列表
            mViewModel.getPlanOrders(mPageNum,mPageSize);
        }
        else if(mTaskState == 5) {  //“已完成”列表现在包括:"已完成(状态为5)，榜单已提交的任务（磅单待审核时任务状态为3,磅单审核不通过时任务状态为4）"
            //获取"已完成"任务列表
            mViewModel.getTaskList("3,4,5", mPageNum, mPageSize,mIsForward);
        }
        else{
            //获取任务列表
            mViewModel.getTaskList(String.valueOf(mTaskState), mPageNum, mPageSize,mIsForward);
        }
    }
}
